var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var roomDB = require('../models/room_datas');
var problemDB = require('../models/problem_datas');
var userDB=require('../models/users_datas')
/**
 * 测试用函数
 * 正式发布前务必删掉此函数
 * 清空题目数据库
 */
router.get('/deleteall', function (req, res, next) {
    roomDB.remove({}, function (err, ret) {
        if (err) {
            console.log("题目数据库清空失败")
            res.end('clear fail')
        } else {
            console.log('题目数据库清空成功');
            res.end('clear success')
        }
    });
})


// router.get('/create', function (req, res, next) {
//     if (req.session.user && req.session.user.status === 1) {
//         var publicProblemSet = []
//         var myPrivateProblemSet = []
//         problemDB.find({
//             status: 0
//         }).then(function (data, err) {
//             if (err) {
//                 console.log('查询失败')
//             } else {
//                 publicProblemSet = data
//             }
//             return problemDB.find({
//                 author_id: req.session.user._id,
//                 status: 1
//             })
//         }).then(function (data, err) {
//             if (err) {
//                 console.log('查询失败')
//             } else {
//                 myPrivateProblemSet = data
//             }
//             res.render('room_create', {
//                 publicProblems: publicProblemSet,
//                 myPrivateProblems: myPrivateProblemSet
//             })
//         })
//     } else {
//         res.json({
//             status: "2",
//             msg: 'Insufficient permission',
//             result: {}
//         });
//     }

// });


router.get('/create/publicproblemselect', function (req, res, next) {
    var pageNum = Number(req.query.pageNum)
    var pageSize = Number(req.query.pageSize)
    var totalPageNum
    if (req.session.user && req.session.user.status === 1) { //用户已登录且为面试官
        if (pageSize <= 0 || pageNum < 1) {
            res.json({
                status: '3',
                msg: 'query value error',
                result: {}
            });
        } else {
            problemDB.find({
                status: 0,
                author_id: {
                    $ne: req.session.user._id
                }
            }).count().then(function (data, err) {
                if (err) {
                    //console.log('查询失败')
                    res.json({
                        status: '500',
                        msg: err.message,
                        result: {}
                    });
                } else {
                    if (data % pageSize == 0) {
                        totalPageNum = data / pageSize
                    } else {
                        totalPageNum = parseInt(data / pageSize) + 1
                    }
                    return problemDB.find({
                        status: 0,
                        author_id: {
                            $ne: req.session.user._id
                        }
                    }).limit(pageSize).skip((pageNum - 1) * pageSize)
                }
            }).then(function (data, err) {
                console.log(data)
                if (err) {
                    res.json({
                        status: '500',
                        msg: err.message,
                        result: {}
                    });
                } else {
                    res.json({
                        status: "1",
                        msg: '',
                        result: {
                            totalPageNum: totalPageNum,
                            problemSet: data
                        }
                    });
                    // res.render('problem_all',{
                    //     problems:data
                    // })
                }
            })
        }
    } else {
        res.json({
            status: "2",
            msg: 'Insufficient permission',
            result: {}
        });
    }
})


router.get('/create/myproblemselect', function (req, res, next) {
    var pageNum = Number(req.query.pageNum)
    var pageSize = Number(req.query.pageSize)
    var totalPageNum
    if (req.session.user && req.session.user.status === 1) { //用户已登录且为面试官
        if (pageSize <= 0 || pageNum < 1) {
            res.json({
                status: '3',
                msg: 'query value error',
                result: {}
            });
        } else {
            problemDB.find({
                author_id: req.session.user._id
            }).count().then(function (data, err) {
                if (err) {
                    //console.log('查询失败')
                    res.json({
                        status: '500',
                        msg: err.message,
                        result: {}
                    });
                } else {
                    if (data % pageSize == 0) {
                        totalPageNum = data / pageSize
                    } else {
                        totalPageNum = parseInt(data / pageSize) + 1
                    }
                    return problemDB.find({
                        author_id: req.session.user._id
                    }).limit(pageSize).skip((pageNum - 1) * pageSize)
                }
            }).then(function (data, err) {
                if (err) {
                    res.json({
                        status: '500',
                        msg: err.message,
                        result: {}
                    });
                } else {
                    res.json({
                        status: "1",
                        msg: '',
                        result: {
                            totalPageNum: totalPageNum,
                            problemSet: data
                        }
                    });
                    // res.render('problem_all',{
                    //     problems:data
                    // })
                }
            })
        }
    } else {
        res.json({
            status: "2",
            msg: 'Insufficient permission',
            result: {}
        });
    }
})



router.post('/create', function (req, res, next) {
    if (req.session.user && req.session.user.status === 1) { //用户已登录且为面试官
        var room = new roomDB({
            creator_id: req.session.user._id,
            room_name: req.body.room_name,
            problemSet: req.body.problem_select,
            finished:0
        });

        room.save(function (err, data) {
            if (err) {
                res.json({
                    status: '500',
                    msg: err.message,
                    result: {}
                });
                console.log("保存失败")
            } else {
                res.json({
                    status: "1",
                    msg: '',
                    result: {
                        room: data
                    }
                });
                //console.log("保存成功")
                //console.log(data)
                //res.redirect('/api/room/myroom')
            }

        });
    } else {
        res.json({
            status: "2",
            msg: 'Insufficient permission',
            result: {}
        });
    }
})


router.get('/myroom', function (req, res, next) {
    var pageNum = Number(req.query.pageNum)
    var pageSize = Number(req.query.pageSize)
    var totalPageNum
    if (req.session.user&& req.session.user.status === 1) {
        if (pageSize <= 0 || pageNum < 1) {
            res.json({
                status: '3',
                msg: 'query value error',
                result: {}
            });
        } else {
            roomDB.find({
                creator_id: req.session.user._id,
                finished:1
            }).count().then(function (data, err) {
                if (err) {

                    //console.log('查询失败')
                    res.json({
                        status: '500',
                        msg: err.message,
                        result: {}
                    });
                } else {
                    if (data % pageSize == 0) {
                        totalPageNum = data / pageSize
                    } else {
                        totalPageNum = parseInt(data / pageSize) + 1
                    }
                    return roomDB.find({
                        creator_id: req.session.user._id,
                        finished:1
                    }).sort({'create_time':-1}).limit(pageSize).skip((pageNum - 1) * pageSize)
                }
            }).then(function (data, err) {
                if (err) {
                    //console.log('查询失败')
                    res.json({
                        status: '500',
                        msg: err.message,
                        result: {}
                    });
                } else {
                    res.json({
                        status: "1",
                        msg: '',
                        result: {
                            totalPageNum: totalPageNum,
                            roomSet: data
                        }
                    });
                    // console.log('我的题目')
                    // console.log(data)
                    // res.render('problem_my',{
                    //     problems:data
                    // })
                }
            })
        }
    } else //用户未登录
    {
        res.json({
            status: "2",
            msg: 'Insufficient permission',
            result: {}
        });
    }
});



router.get('/problemall', function (req, res, next) {
    var room_id = req.query.rid
    if (req.session.user) {
        roomDB.findOne({
            _id: room_id
        }, function (err, data) {
            if (err) {
                res.json({
                    status: '500',
                    msg: err.message,
                    result: {}
                });
                //console.log('查询失败');
            } else {
                // console.log(ret)
                if(data){
                //console.log("problem all",data.problemSet)
                problemDB.find({
                    _id: {
                        "$in": data.problemSet
                    }
                }, function (err, data1) {
                    if (err) {
                        res.json({
                            status: '500',
                            msg: err.message,
                            result: {}
                        });
                        //console.log('查询失败');
                    } else {
                        res.json({
                            status: '1',
                            msg: '',
                            result: {
                                problemSet: data1
                            }
                        });
                    }
                })
            }
            else
            {
                res.json({
                    status: '0',
                    msg: 'not found',
                    result: {
                        problemSet: []
                    }
                });
            }

            }
        });
    } else //用户未登录
    {
        res.json({
            status: "2",
            msg: 'Insufficient permission',
            result: {}
        });
    }
})


router.get('/delete', function (req, res, next) {
    var room_id = req.query.rid
    roomDB.findOne({
        _id: room_id
    }, function (err, data) {
        if (err) {
            res.json({
                status: '500',
                msg: err.message,
                result: {}
            });
            //console.log('查询失败');
        } else {
            if (data&&data.finished==1) {
                if (req.session.user && req.session.user._id == data.creator_id) { //只有作者可以获取题目信息
                    roomDB.remove({
                        _id: room_id
                    }, function (err, data1) {

                        if (err) {
                            res.json({
                                status: '500',
                                msg: err.message,
                                result: {}
                            });
                        } else {
                            console.log('删除成功');
                            res.json({
                                status: "1",
                                msg: '',
                                result: {
                                    deleteData: data1
                                }
                            });
                        }
                        //res.redirect('/api/problem/myproblem')
                    });
                } else {
                    res.json({
                        status: "2",
                        msg: 'Insufficient permission',
                        result: {}
                    });
                }

            } else {
                res.json({
                    status: "0",
                    msg: 'not found',
                    result: {}
                });
            }
            // console.log(ret)
            // res.render('problem_detail', { problem_title: ret.title ,problem_content:ret.content});
        }
    });
})


router.get('/deleteproblem', function (req, res, next) {
    var room_id = req.query.rid
    var problem_id = req.query.pid
    roomDB.findOne({
        _id: room_id
    }, function (err, data) {
        if (err) {
            res.json({
                status: '500',
                msg: err.message,
                result: {}
            });
            //console.log('查询失败');
        } else {
            if (data) {
                if (data.finished == 0) {
                    let newProblemSet = data.problemSet.remove(problem_id)
                    if (req.session.user && req.session.user._id == data.creator_id) { //只有作者可以获取题目信息
                        roomDB.findByIdAndUpdate(room_id, {
                            problemSet: newProblemSet
                        }, function (err, data1) {
                            if (err) {
                                console.log('删除失败', err);
                                res.json({
                                    status: '500',
                                    msg: err.message,
                                    result: {}
                                });
                            } else {
                                console.log('删除成功');
                                res.json({
                                    status: "1",
                                    msg: '',
                                    result: {
                                        deleteData: data1
                                    }
                                });
                            }
                        })
                    } else {
                        res.json({
                            status: "2",
                            msg: 'Insufficient permission',
                            result: {}
                        });
                    }
                }
                else
                {
                    res.json({
                        status: "2",
                        msg: 'Insufficient permission',
                        result: {}
                    });
                }

            } else {
                res.json({
                    status: "0",
                    msg: 'not found',
                    result: {}
                });
            }
            // console.log(ret)
            // res.render('problem_detail', { problem_title: ret.title ,problem_content:ret.content});
        }
    });
})

router.post('/updateproblem', function (req, res, next) {
    var room_id = req.body.rid
    roomDB.findOne({
        _id: room_id
    }, function (err, data) {
        if (err) {
            res.json({
                status: '500',
                msg: err.message,
                result: {}
            });
            //console.log('查询失败');
        } else {
            if (data) {
                if (data.finished == 0) {
                    if (req.session.user && req.session.user._id == data.creator_id) { //只有作者可以获取题目信息
                        roomDB.findByIdAndUpdate(room_id, {
                            problemSet: req.body.problemSet
                        }, function (err, data1) {
                            if (err) {
                                res.json({
                                    status: '500',
                                    msg: err.message,
                                    result: {}
                                });
                            } else {
                                res.json({
                                    status: "1",
                                    msg: '',
                                    result: {
                                        updateData: data1
                                    }
                                });
                            }
                        })
                    } else {
                        res.json({
                            status: "2",
                            msg: 'Insufficient permission',
                            result: {}
                        });
                    }
                }
                else {
                    res.json({
                        status: "2",
                        msg: 'Insufficient permission',
                        result: {}
                    });
                }

            } else {
                res.json({
                    status: "0",
                    msg: 'not found',
                    result: {}
                });
            }
            // console.log(ret)
            // res.render('problem_detail', { problem_title: ret.title ,problem_content:ret.content});
        }
    });
})


router.get('/exist', function (req, res, next) {
    var room_id = req.query.rid
    roomDB.findOne({
        _id: room_id
    }, function (err, data) {
        if (err) {
            res.json({
                status: '500',
                msg: err.message,
                result: {}
            });
            //console.log('查询失败');
        } else {
            if (data) {
                res.json({
                    status: "1",
                    msg: '',
                    result: {
                        exist:true
                    }
                });

            } else {
                res.json({
                    status: "0",
                    msg: 'not found',
                    result: {
                        exist:false
                    }
                });
            }
            // console.log(ret)
            // res.render('problem_detail', { problem_title: ret.title ,problem_content:ret.content});
        }
    });
})

router.get('/finished', function (req, res, next) {
    var room_id = req.query.rid
    roomDB.findOne({
        _id: room_id
    }, function (err, data) {
        if (err) {
            res.json({
                status: '500',
                msg: err.message,
                result: {}
            });
            //console.log('查询失败');
        } else {
            if (data) {
                res.json({
                    status: "1",
                    msg: '',
                    result: {
                        finished:data.finished
                    }
                });

            } else {
                res.json({
                    status: "0",
                    msg: 'not found',
                    result: {}
                });
            }
            // console.log(ret)
            // res.render('problem_detail', { problem_title: ret.title ,problem_content:ret.content});
        }
    });
})

router.get('/finish', function (req, res, next) {
    var room_id = req.query.rid
    console.log("room_id",room_id);
    roomDB.findOne({
        _id: room_id
    }, function (err, data) {
        if (err) {
            res.json({
                status: '500',
                msg: err.message,
                result: {}
            });
            //console.log('查询失败');
        } else {
            console.log("finish",data)
            if (data) {
                if (data.finished == 0) {
                    if (req.session.user && req.session.user._id == data.creator_id) { //只有作者可以获取题目信息
                        roomDB.findByIdAndUpdate(room_id, {
                            finished: 1
                        }, {new:true},function (err, data1) {
                            if (err) {
                                res.json({
                                    status: '500',
                                    msg: err.message,
                                    result: {}
                                });
                            } else {
                                res.json({
                                    status: "1",
                                    msg: '',
                                    result: {
                                        updateData: data1
                                    }
                                });
                            }
                        })
                    } else {
                        res.json({
                            status: "2",
                            msg: 'Insufficient permission',
                            result: {}
                        });
                    }
                }
                else {
                    res.json({
                        status: "2",
                        msg: 'Insufficient permission',
                        result: {}
                    });
                }

            } else {
                res.json({
                    status: "0",
                    msg: 'not found',
                    result: {}
                });
            }
            // console.log(ret)
            // res.render('problem_detail', { problem_title: ret.title ,problem_content:ret.content});
        }
    });
})


router.get('/enter', function (req, res, next) {
    var room_id = req.query.rid
    console.log("room_id",room_id)
    console.log("room_id",room_id);
    roomDB.findOne({
        _id: room_id
    }, function (err, data) {
        if (err) {
            res.json({
                status: '500',
                msg: err.message,
                result: {}
            });
            //console.log('查询失败');
        } else {
            if (data) {
                if (data.finished == 0) {
                    //console.log("enter data",data)
                if(req.session.user){
                    if (data.intervieweeSet.indexOf(req.session.user._id) > -1) {
                        res.json({
                            status: "1",
                            msg: '',
                            result: {
                                updateData: data
                            }
                        });
                    } else {
                        let newIntervieweeSet=data.intervieweeSet
                        newIntervieweeSet.push(req.session.user._id)
                        //console.log("newIntervieweeSet",newIntervieweeSet)
                        roomDB.findByIdAndUpdate(room_id, {
                            intervieweeSet: newIntervieweeSet
                        },  {new:true},function (err, data1) {
                            if (err) {
                                res.json({
                                    status: '500',
                                    msg: err.message,
                                    result: {}
                                });
                            } else {
                                console.log("enter data",data1)
                                res.json({
                                    status: "1",
                                    msg: '',
                                    result: {
                                        updateData: data1
                                    }
                                });
                            }
                        })
                    }
                }
                else
                {
                    res.json({
                        status: "2",
                        msg: 'Insufficient permission',
                        result: {}
                    });
                }
                }
                else
                {
                    res.json({
                        status: "2",
                        msg: 'Insufficient permission',
                        result: {}
                    });
                }

            } else {
                res.json({
                    status: "0",
                    msg: 'not found',
                    result: {}
                });
            }
            // console.log(ret)
            // res.render('problem_detail', { problem_title: ret.title ,problem_content:ret.content});
        }
    });
})

router.get('/intervieweeall', function (req, res, next) {
    var room_id = req.query.rid
    if (req.session.user&& req.session.user.status === 1) {
        roomDB.findOne({
            _id: room_id
        }, function (err, data) {
            if (err) {
                res.json({
                    status: '500',
                    msg: err.message,
                    result: {}
                });
                //console.log('查询失败');
            } else {
                // console.log(ret)
                if(data){
                console.log("intervieweeSet all",data.intervieweeSet)
                userDB.find({
                    _id: {
                        "$in": data.intervieweeSet
                    }
                }, function (err, data1) {
                    if (err) {
                        res.json({
                            status: '500',
                            msg: err.message,
                            result: {}
                        });
                        //console.log('查询失败');
                    } else {
                        res.json({
                            status: '1',
                            msg: '',
                            result: {
                                intervieweeSet: data1
                            }
                        });
                    }
                })
            }
            else
            {
                res.json({
                    status: '0',
                    msg: 'not found',
                    result: {
                        problemSet: []
                    }
                });
            }

            }
        });
    } else //用户未登录
    {
        res.json({
            status: "2",
            msg: 'Insufficient permission',
            result: {}
        });
    }
})

module.exports = router;